package org.os.springboot.extensions.document.swagger;

import com.google.common.base.Predicates;

import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

import org.os.springboot.extensions.document.swagger.entity.SwaggerProps;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * swagger配置
 */
@Slf4j
@ConditionalOnProperty(prefix = "spring.document", name = "enable", havingValue = "true")
@EnableSwagger2
@Configuration
public class SwaggerConfig {

    @Resource
    private SwaggerProps props;

    @Bean
    public Docket api() {
        log.info("已启用swagger文档: {}", props);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .ignoredParameterTypes(Session.class)
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(Predicates.not(PathSelectors.regex(
                        props.getExcludeRegex())))
                .paths(PathSelectors.any())
                .build();
    }

    /**
     * 接口信息
     * 
     * @return
     */
    private ApiInfo apiInfo() {
        Contact contact = null;
        if (null != props.getContact()) {
            contact = new Contact(props.getContact().getName(), props.getContact().getUrl(),
                    props.getContact().getEmail());
        }
        return new ApiInfoBuilder()
                .title(props.getTitle())
                .description(props.getLicense())
                .contact(contact)
                .termsOfServiceUrl(props.getTermsOfServiceUrl())
                .license(props.getLicense())
                .licenseUrl(props.getLicenseUrl())
                // .extensions(props.getExtension())
                .version(props.getVersion())
                .build();
    }

}
